package com.time.on.device.service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.app.admin.DevicePolicyManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.CountDownTimer;
import android.os.IBinder;
import android.os.PowerManager;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.time.on.device.R;
import com.time.on.device.activity.TimeConfigActivity;
import com.time.on.device.model.DataConfig;
import com.time.on.device.screen.ScreenReceiver;

public class TimerService extends Service {

	private static final String TAG_SERVICE_ERROR = "TimerServiceError";
	public static final int NOTIFICATION_ID = 12345;
	public static long timeRemain;// To display on configuration screen
	private long timeToCount;
	private boolean isLocked = false;
	private String messageInform = "";
	private static final long INTERVAL_COUNT_DOWN = 1000l;// 1s
	private static final long WAIT_TIME = 3000l;// 3s
	private CountDown countDown;
	private BroadcastReceiver screenReceiver;

	@Override
	public void onCreate() {

		super.onCreate();
		// Register receiver to handle screen on and screen off logic
		IntentFilter intentFilter = new IntentFilter(Intent.ACTION_SCREEN_ON);
		intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
		screenReceiver = new ScreenReceiver();
		registerReceiver(screenReceiver, intentFilter);
		// Get data configuration for service
		DataConfig dataConfig = new DataConfig(this);
		messageInform = dataConfig.getMessageConfig();
		timeToCount = dataConfig.getTimeConfig();
		isLocked = dataConfig.isLockedScreen();
	}

	@Override
	public void onStart(Intent intent, int startId) {

		Boolean screenOn = true;
		if (intent != null) {
			screenOn = intent.getBooleanExtra("screen_state", true);
		}
		if (screenOn) {
			startCountDown();
		} else {
			stopCountDown();
		}
		
	}

	private boolean isScreenOn() {
		PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
		if (powerManager.isScreenOn()) {
			return true;
		} else {
			return false;
		}
	}

	private void stopCountDown() {

		if (countDown != null) {
			countDown.cancel();
		}
	}

	private void startCountDown() {
		// Double check if screen is on
		if (isScreenOn()) {
			// Stop current instance
			stopCountDown();
			// Reset remain time
			timeRemain = 0;
			// before starting new one
			countDown = new CountDown(this, timeToCount, INTERVAL_COUNT_DOWN);
			countDown.start();
		}	

	}

	@Override
	public void onDestroy() {

		stopCountDown();
		if (screenReceiver != null) {
			unregisterReceiver(screenReceiver);
		}	

	}

	public void createNotification() {

		try {

			NotificationCompat.Builder builder = new NotificationCompat.Builder(
					this)
					.setSmallIcon(R.drawable.clock_icon)
					.setContentTitle(
							getResources().getString(R.string.app_name))
					.setContentText(messageInform);

			Intent targetIntent = new Intent(this, TimeConfigActivity.class);

			PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
					targetIntent, PendingIntent.FLAG_UPDATE_CURRENT);
			builder.setContentIntent(contentIntent);
			Notification notification = builder.build();
			notification.defaults = Notification.DEFAULT_VIBRATE;

			NotificationManager nManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
			nManager.notify(NOTIFICATION_ID, notification);

		} catch (Exception ex) {

			Log.e(TAG_SERVICE_ERROR, "Notification could not create because: "
					+ ex.getMessage());
		}

	}

	public static void clearNotification(Context context) {
		try {
			String ns = Context.NOTIFICATION_SERVICE;
			NotificationManager notificationManager = (NotificationManager) context
					.getSystemService(ns);
			notificationManager.cancel(TimerService.NOTIFICATION_ID);
		} catch (Exception ex) {
			Log.e(TAG_SERVICE_ERROR, "Could not clear notification because: "
					+ ex.getMessage());
		}
	}

	public class CountDown extends CountDownTimer {

		private Context context;

		public CountDown(Context context, long millisInfuture,
				long countDownInterval) {
			super(millisInfuture, countDownInterval);
			this.context = context;
		}

		@Override
		public void onFinish() {

			createNotification();
			if (isLocked) {
				try {

					Thread.sleep(WAIT_TIME);

					DevicePolicyManager devicePolicyManager = (DevicePolicyManager) this.context
							.getSystemService(Context.DEVICE_POLICY_SERVICE);
					devicePolicyManager.lockNow();

				} catch (Exception ex) {

					Log.e(TAG_SERVICE_ERROR,
							"Fail to lock screen: " + ex.toString());
				}

			}
			// Reset count down from beginning when time is over
			startCountDown();
			
		}

		@Override
		public void onTick(long millisUntilFinished) {

			long millis = millisUntilFinished;
			timeRemain = millis;

		}

	}

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

}
